package cn.itcast.bos.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage("json-default")
@Namespace("/")
@Actions
@Controller
@Scope("prototype")
public class AreaAction extends BaseAction<Area> {

	private static final long serialVersionUID = 1L;


	@Autowired
	private AreaService areaService;

	// 获取页面上传的文件
	private File file;
	private String fileFileName;
	private String fileContentType;

	public void setFile(File file) {
		this.file = file;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	@Action(value = "area_import", results = { @Result(name = "success", type = "json") })
	public String importArea() throws Exception {
		// System.out.println("file:"+file);
		// System.out.println("fileFileName:"+fileFileName);
		// System.out.println("fileContentType:"+fileContentType);
		List<Area> list = new ArrayList<Area>();
		// 加载excel文件对象
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		// 读取一个sheet
		HSSFSheet sheet = hssfWorkbook.getSheetAt(0);// 获取第一个sheet对象
		// 读取sheet中每一行,一行数据对象一个区域对象
		for (Row row : sheet) {
			// 第一行表头跳过
			if (row.getRowNum() == 0) {
				continue;
			}
			// 跳过空值的行
			if (row.getCell(0) != null && StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());
			// 基于pinyin4j生成城市编码和解码
			String province = area.getProvince().substring(0, area.getProvince().length() - 1);// 去掉"省/市"
			String city = area.getCity().substring(0, area.getCity().length() - 1);// 去掉"市/州"
			String district = area.getDistrict().substring(0, area.getDistrict().length() - 1);// 去掉"县,区"
			// 简码
			String[] headArray = PinYin4jUtils.getHeadByString(province + city + district);
			StringBuffer buffer = new StringBuffer();
			for (String headStr : headArray) {
				buffer.append(headStr);
			}
			String shortcode = buffer.toString();
			area.setShortcode(shortcode);
			// 城市编码
			String citycode = PinYin4jUtils.hanziToPinyin(city, "");
			area.setCitycode(citycode);
			list.add(area);
		}

		areaService.saveAreas(list);
		return SUCCESS;
	}

	

	@Action(value = "area_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		// 有条件的查询
		Pageable pageable = new PageRequest(page - 1, rows);
		// 组织查询条件
		Specification<Area> specification = new Specification<Area>() {

			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate predicate = null;
				List<Predicate> list = new ArrayList<Predicate>();
				// 快递员工号
				if (StringUtils.isNotBlank(model.getProvince())) {
					Predicate p = cb.like(root.get("province").as(String.class), "%" + model.getProvince() + "%");
					list.add(p);
				}
				// 所属单位
				if (StringUtils.isNotBlank(model.getCity())) {
					Predicate p = cb.like(root.get("city").as(String.class), "%" + model.getCity() + "%");
					list.add(p);
				}
				// 快递员类型
				if (StringUtils.isNotBlank(model.getDistrict())) {
					Predicate p = cb.like(root.get("district").as(String.class), "%" + model.getDistrict() + "%");
					list.add(p);
				}

				if (list != null && list.size() > 0) {
					Predicate[] p = new Predicate[list.size()];
					query.where(list.toArray(p));
				}
				//按照id降序
				query.orderBy(cb.desc(root.get("id").as(String.class)));
				return query.getRestriction();
			}

		};

		Page<Area> page = areaService.findPageQueryCondition(specification, pageable);
		pushPageDataToValueStack(page);
		return SUCCESS;
		
	}

	
}
